package com.maxd.service.pay;

import com.maxd.adapter.LoginUserHolder;
import com.maxd.constants.PayScene;
import com.maxd.model.PayRecord;
import com.maxd.respository.PayRecordRepository;
import com.maxd.utils.JsonUtils;
import com.maxd.utils.SeqUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Slf4j
@Service
public class PayRecordService implements IPayRecordService {

    @Autowired
    private PayRecordRepository payRecordRepository;

    private static final String descPrefix = "戎威少年 ";

    @Override
    public PayRecord queryByPaySeq(String paySeq) {
        return payRecordRepository.findById(paySeq).orElse(null);
    }
    @Override
    public PayRecord savePayRecord(String businessId, BigDecimal payAmt, String description, PayScene payScene) {
        PayRecord payRecord = new PayRecord();
        payRecord.setPaySeq(SeqUtils.dateSeq());
        payRecord.setUserId(LoginUserHolder.getUserId());
        // 暂时写死
        payRecord.setPayWay("WX_JSAPI");
        payRecord.setPayAmount(payAmt);
        // 描述进行处理，增加前缀，截取长度
        payRecord.setDescription(getDesc(description));
        payRecord.setPayScene(payScene.getCode());
        payRecord.setBusinessId(businessId);
        payRecord.setPayStatus("0");
        payRecord.setCreateBy(String.valueOf(payRecord.getUserId()));
        payRecord.setUpdateBy(String.valueOf(payRecord.getUserId()));
        log.info("插入支付流水记录:{}", JsonUtils.toJsonString(payRecord));
        payRecordRepository.save(payRecord);
        return payRecord;
    }
    @Override
    public Integer updateStatus(String paySeq, String payStatus) {
        return payRecordRepository.updateStatus(paySeq, payStatus);
    }

    public Integer updatePaySuccess(String paySeq, String transactionId) {
        return payRecordRepository.updatePaySuccess(paySeq, transactionId);
    }

    private String getDesc(String description) {
        String desc = StringUtils.hasText(description) ? descPrefix + description : descPrefix + "下单支付";
        if(desc.length() > 127) {
            desc = desc.substring(0, 127);
        }
        return desc;
    }

}
